package com.tenqian.crm.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.tenqian.AlipayConfig;
import com.tenqian.Result;
import com.tenqian.crm.domain.TqUser;
import com.tenqian.crm.service.OrderService;
import com.tenqian.crm.service.TqUserService;
import com.tenqian.order.domain.Order;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/order")
public class OrderController {
    static Logger logger = LoggerFactory.getLogger(OrderController.class);
    @Autowired
    OrderService orderService;
    @Autowired
    TqUserService tqUserService;

    @RequestMapping("/getSign")
    @ResponseBody
    public Result getSign(String productCode, String token) {
        return orderService.getSign(productCode, token);
    }

    @RequestMapping("/delOrder")
    @ResponseBody
    public Result getSign(@RequestParam("id") String id) {
        return orderService.delOrder(id);
    }


    @RequestMapping("/aliNotify")
    @ResponseBody
    public String aliNotify(HttpServletRequest request) {
        //验证通过
        if (checkSum(request)) {
            String out_trade_no = request.getParameter("out_trade_no");
            //保存用户支付宝号
            Order order = orderService.findOrderById(out_trade_no);
            order.setBuyer_logon_id(request.getParameter("buyer_logon_id"));
            order.setStatus(1);//修改为已支付
            setPastDate(order);//设置过期时间
            orderService.save(order);
            //更新用户的vip状态
            TqUser userById = (TqUser) tqUserService.findUserById(order.getUserId()).getData();
            userById.setIsVip(1);
            tqUserService.update(userById);
            return "success";
        }
        return "fail";
    }

    private void setPastDate(Order order) {
        Date date = new Date();// 取时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.MONTH, order.getDuration());// 把日期往后增加. 整数往后推, 负数往前移动
        order.setPastDate(calendar.getTime());
    }

    private boolean checkSum(HttpServletRequest request) {
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            return AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
        } catch (AlipayApiException e) {
            logger.error("支付宝验证失败", e);
            e.printStackTrace();
        }
        return false;
    }
}
